package infrastructure

import (
	"bytes"
	"crypto/cipher"
	"crypto/des"
	"encoding/base64"
	"fmt"
	"strings"
)

func encrypt(src []byte, key []byte) []byte {
	block, err := des.NewCipher(key)
	if err != nil {
		panic(err)
	}
	src = PKCS5Padding(src, block.BlockSize())
	ciphertext := make([]byte, len(src))
	blockMode := cipher.NewCBCEncrypter(block, key)
	blockMode.CryptBlocks(ciphertext, src)
	return ciphertext
}

func decrypt(src []byte, key []byte) []byte {
	block, err := des.NewCipher(key)
	if err != nil {
		panic(err)
	}
	blockMode := cipher.NewCBCDecrypter(block, key)
	origData := make([]byte, len(src))
	blockMode.CryptBlocks(origData, src)
	origData = PKCS5UnPadding(origData)
	return origData
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func PKCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}

func extractHash(hash string) []string {
	if hash == "" {
		return nil
	}
	key := []byte("183lizhi")
	//src := []byte(hash)
	src, err := base64.StdEncoding.DecodeString(hash)
	if err != nil {
		panic(err)
	}
	ck := decrypt(src, key)
	items := strings.Split(string(ck), "|")
	for i := 0; i < len(items); i++ {
		items[i] = strings.TrimSpace(items[i])
	}
	return items
}

func main2() {
	key := []byte("183lizhi")
	src := []byte("12321312")
	encrypted := encrypt(src, key)
	encryptedBase64 := base64.StdEncoding.EncodeToString(encrypted)
	fmt.Println("Encrypted:", encryptedBase64)

	decrypted, err := base64.StdEncoding.DecodeString(encryptedBase64)
	if err != nil {
		panic(err)
	}
	decrypted = decrypt(decrypted, key)
	fmt.Println("Decrypted:", string(decrypted))

	decrypted2 := extractHash("Za7uRqKxK6ht-crC5jzxR1WC77v8Wqmo")

	fmt.Println("Decrypted2:", decrypted2)

}
